package xyz.jcat.common.util;

import org.springframework.cglib.beans.BeanCopier;

import java.util.HashMap;
import java.util.Map;

public class CopyUtils {

    private static final Map<String, BeanCopier> BEAN_COPIER_CACHE = new HashMap<>();

    /**
     * 复制对象属性
     *
     * @param source 数据来源对象
     * @param target 目标对象
     */
    public static <D> D copy(Object source, D target) {
        if (source == null || target == null)
            return null;
        Class sourceClass = source.getClass();
        Class targetClass = target.getClass();
        String key = sourceClass.getName() + "-" + targetClass.getName();
        BeanCopier beanCopier = BEAN_COPIER_CACHE.get(key);
        if (beanCopier == null)
            beanCopier = BeanCopier.create(sourceClass, targetClass, false);

        beanCopier.copy(source, target, null);
        return target;
    }

}
